<template>
    <view style="border: solid 1px white">
        <view class="register-page">
            <uni-forms ref="registerForm" :rules="registerRules" :model="registerFormData">
                <uni-forms-item onFieldChange name="userPhone">
                    <uni-easyinput v-model="registerFormData.userPhone" type="number" placeholder="手机号" placeholderStyle="color: #DDD" :maxlength=11 />
                </uni-forms-item>

                <uni-forms-item name="userEmail">
                    <uni-easyinput v-model="registerFormData.userEmail" type="email" placeholder="邮箱" placeholderStyle="color: #DDD"/>
                </uni-forms-item>

                <uni-forms-item name="userPassword">
                    <uni-easyinput v-model="registerFormData.userPassword" type="password" placeholder="密码" placeholderStyle="color: #DDD"/>
                </uni-forms-item>

                <uni-forms-item name="authCode">
                    <uni-easyinput v-model="registerFormData.authCode" type="number" placeholder="验证码" placeholderStyle="color: #DDD" :maxlength=6 />
                </uni-forms-item>
            </uni-forms>
            <button v-if="this.showRegisterBtn && this.registerFormData.authCode.length !== null && this.registerFormData.authCode.length > 0" type="primary" class="registerBtn" @click="register('registerForm')">注册</button>
            <button v-else type="primary" class="authCodeBtn" :disabled="authCodeBtnDisable" @click="getAuthCode('registerForm')">{{this.authCodeBtnText}}</button>
        </view>
    </view>

    <uni-popup ref="registerResultDialog" type="dialog">
        <uni-popup-dialog
            :mode="dialog.mode"
            :type="dialog.type"
            :confirmText="dialog.confirmText"
            :title="dialog.title"
            :content="dialog.content"
            :maxlength=11
            value=""
            placeholder="新手机号"
            :showClose="false"
            :before-close="true"
            @confirm="dialogConfirm" />
    </uni-popup>
</template>

<script>
import {register, getAuthCode} from "../../js/api/user";

import UniFormsItem from "../../uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import UniEasyinput from "../../uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import UniForms from "../../uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import {loading, hide, toast, modal} from "../../js/utils/showTip";
import UniPopup from "../../uni_modules/uni-popup/components/uni-popup/uni-popup.vue";
import UniPopupDialog from "../../uni_modules/uni-popup/components/uni-popup-dialog/uni-popup-dialog.vue";

export default {
    name: "register",
    components: {UniPopupDialog, UniPopup, UniForms, UniEasyinput, UniFormsItem},
    data() {
        return {
            registerFormData: {
                userPhone: '',
                userEmail: '',
                userPassword: '',
                authCode: '',
            },
            authCodeBtnDisable: false,
            showRegisterBtn: false,
            authCodeBtnText: '获取验证码',
            registerRules: {
                userPhone: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入手机号'
                        },
                        {
                            validateFunction: function (rule, value, data, callback) {
                                var phoneRegex = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/;
                                if (!phoneRegex.test(value)) {
                                    callback('请输入正确的手机号')
                                }
                                return true
                            }
                        }
                    ]
                },
                userEmail: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入邮箱地址'
                        },
                        {
                            format: 'email',
                            errorMessage: '请输入正确的邮箱地址'
                        }
                    ]
                },
                userPassword: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入密码'
                        },
                        {
                            minLength: 6,
                            maxLength: 18,
                            errorMessage: '密码长度在 {minLength} 到 {maxLength} 个字符',
                        }
                    ]
                }
            },
            dialog: {
                mode: '',
                type: '',
                title: '',
                content: '',
                confirmText: ''
            }
        }
    },
    methods: {
        register(ref) {
            this.$refs[ref].validate().then(res => {
                loading("注册中...", true)
                register(res).then(response => {
                    hide()
                    if (response.code === 200) {
                        this.dialog.mode = 'base'
                        this.dialog.type = 'SUCCESS';
                        this.dialog.title = '注册成功'
                        this.dialog.content = `注册成功，快去登录吧!\n 平台账号：${response.data}`
                        this.dialog.confirmText = '去登录'
                        this.$refs.registerResultDialog.open()
                    } else if (response.code === 15005) {
                        this.dialog.mode = 'input'
                        this.dialog.type = 'WARN';
                        this.dialog.title = `${response.message}`
                        this.dialog.confirmText = '注册'
                        this.$refs.registerResultDialog.open()
                    } else {
                        toast(response.message, 'none', true, 1600)
                    }
                }).catch(response => {
                    toast('服务器开小差了！！！', 'ERROR', true, 1600)
                    this.showRegisterBtn = false
                })
            }).catch(err =>{
            })
        },
        getAuthCode(ref) {
            this.$refs[ref].validateField(['userPhone']).then(res => {
                this.authCodeBtnDisable = true
                let timeNumber = 60
                var interval = setInterval(() => {
                    let times = --timeNumber
                    timeNumber = times < 10 ? '0' + times : times //小于10秒补 0
                    this.authCodeBtnText = timeNumber + "" + "秒后再次获取"
                }, 1000)
                setTimeout(() => {
                    clearInterval(interval)
                    this.authCodeBtnText = '获取验证码';
                    this.authCodeBtnDisable = false;
                }, 60000)
                getAuthCode(res.userPhone, 1).then(response => {
                    if (response.code === 200) {
                        toast("已发送", "SUCCESS", true, 1500)
                        this.showRegisterBtn = true
                    } else {
                        toast(response.message, "ERROR", true, 1500)
                    }
                })
            })
        },
        dialogConfirm(val) {
            if (this.dialog.mode === 'base') {
                uni.redirectTo({
                    url: '/pages/login/login'
                })
            } else {
                let phoneRegex = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/;
                if (!phoneRegex.test(val)) {
                    toast('手机号错误', 'error', true, 1000)
                    return;
                }
                this.registerFormData.userPhone = val
                this.$refs['registerForm'].formData.userPhone =val
                this.register('registerForm')
            }
        }
    }
}
</script>

<style scoped lang="scss">
.register-page {
    padding: 15px;
    background-color: #fff;
    margin-top: 40%;
}
.registerBtn, .authCodeBtn {
    border-radius: 25px;
    background-color: #1989FA;
}
</style>